package com.aliyun.heiyu.powermaster.server.rbac.service.impl;

import com.aliyun.heiyu.common.util.HttpUtil;
import com.aliyun.heiyu.common.util.PropertiesUtil;
import com.aliyun.heiyu.common.util.StringUtil;
import com.aliyun.heiyu.common.util.TimeConvertUtil;
import com.aliyun.heiyu.powermaster.proto.OutRequest;
import com.aliyun.heiyu.powermaster.server.dao.enums.UserErrorEnum;
import com.aliyun.heiyu.powermaster.server.factory.MasterThreadFactory;
import com.aliyun.heiyu.powermaster.server.rbac.dao.TokenMangerDao;
import com.aliyun.heiyu.powermaster.server.rbac.dao.impl.TokenMangerDaoImpl;
import com.aliyun.heiyu.powermaster.server.rbac.object.dto.OutDTO;
import com.aliyun.heiyu.powermaster.server.rbac.service.TokenManager;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.*;

public class TokenManagerImpl implements TokenManager {
    private static Logger logger = LoggerFactory.getLogger(TokenManagerImpl.class);

    private TokenMangerDao tokenMangerDao;
    private String appid = PropertiesUtil.getValue("userConfig.properties", "appid");
    private String sessionUrl = PropertiesUtil.getValue("userConfig.properties", "sessionUrl");
    public static  Map<String, OutDTO> userList = new ConcurrentHashMap();

    public TokenManagerImpl(){
        this.tokenMangerDao = new TokenMangerDaoImpl();
        jobTime();
    }


    //间隔10s获取isc系统设置时间，
    public void jobTime() {
        final Calendar instance = Calendar.getInstance();
    ThreadPoolExecutor executorService = new ThreadPoolExecutor(1, 1,
        60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new MasterThreadFactory("TOKEN"));
        executorService.execute(new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    List<Map<String, String>> maps = tokenMangerDao.listToken();
                    if (null != maps && maps.size() !=0) {
                        for (Map<String, String> map : maps){
                            String token = map.get("token");
                            if (StringUtil.isEmpty(token)) {
                                continue;
                            }
                            if(!doValidate(token)){
                                boolean remove = remove(token);
                                if (!remove) {
                                    logger.error("token删除失败");
                                    continue;
                                }
                            }
                        }
                    }
                }catch (Exception e){
                    logger.error("token监听失败，错误为" + e.getMessage() + ",");
                }
                    try {
                        Thread.sleep(2 * 1000);
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage(), e);
                    }
            }
        }
    });
    }

    @Override
    public void createUserIp(String ip, String token) {
    }

    public int checkToken(String tokenId){
        if("market_token".equals(tokenId)){
            logger.info("market 信息通信");
            return 0;
        }
        if (StringUtil.isEmpty(tokenId)) {
            logger.info("token 为空+++++++");
            return UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode();
        }

        Map<String, String> dataMap = tokenMangerDao.findByToken(tokenId);
        if(dataMap == null){
            //token缺失
            logger.info("token 找不到对应数据+++++" + tokenId);
            return UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode();
        }
        if(!doValidate(tokenId)){
            //token 过期或无效
            logger.info("token 已经过期");
            return UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode();
        }
        tokenMangerDao.updateToken(tokenId);
        return 0;
    }

    public int checkToken(String tokenId, String refresh){
        if("market_token".equals(tokenId)){
            logger.info("market 信息通信");
            return 0;
        }
        if (StringUtil.isEmpty(tokenId)) {
            logger.info("token 为空+++++++");
            return UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode();
        }
        Map<String, String> dataMap = tokenMangerDao.findByToken(tokenId);
        if(dataMap == null){
            //token缺失
            logger.info("token 缺失+++++" + tokenId);
            return UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode();
        }
        if(!doValidate(tokenId)){
            //token 过期或无效
            logger.info("token 已经过期");
            return UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode();
        }
        if (!"1".equals(refresh)) {
            tokenMangerDao.updateToken(tokenId);
        }
        return 0;
    }

    @Override
    public int checkUserIp(String userIp, String userName) {
        return 0;
    }

    public boolean remove(String token){
        Map<String, String> map = tokenMangerDao.findByToken(token);
        if(null == map || map.size() == 0){
            return true;
        }
        String data = map.get("data");
        if (StringUtil.isEmpty(data)){
            return false;
        }
        return tokenMangerDao.destroy(data);
    }

    /**
     * 关闭浏览器定时退出
     * @param request
     * @return
     */
    @Override
    public void removeToken(OutRequest request) {
        if(null == request || StringUtil.isEmpty(request.getUsername())){
            return;
        }
        OutDTO outDTO = new OutDTO();
        if(!StringUtil.isEmpty(request.getToken())){
            outDTO.setToken(request.getToken());
        }
        if(!StringUtil.isEmpty(request.getService())){
            outDTO.setService(request.getService());
        }
        if(!StringUtil.isEmpty(request.getIscUserId())){
            outDTO.setIscUserId(request.getIscUserId());
        }
        outDTO.setOutTime(System.currentTimeMillis());
        outDTO.setUsername(request.getUsername());
        userList.put(request.getUsername(),outDTO);
        logger.info("添加关闭用户退出方法：{}",outDTO);
    }

    @Override
    public int getUserStatus(String tokenId) {
        return 1;
    }

    private void validate(){

    }

    private boolean doValidate(String token){
        String sessionTimeout = "1800";
        if (StringUtil.isEmpty(token)) {
            return false;
        }
        JSONObject jsonObject = null;
        Object obj = null;
        try {
            jsonObject = HttpUtil.getRequest(sessionUrl + "?appid=" + appid + "");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取isc会话时间异常，" + e.toString());
            return true;
        }
        if (null == jsonObject ) {
            sessionTimeout = "1800";
        } else {
            obj = jsonObject.get("sessionTimeout");
            if (null == obj ) {
                sessionTimeout = "1800";
            } else {
                sessionTimeout = obj.toString();
            }
        }
        logger.info("获取到isc配置会话超时时间为" + sessionTimeout);
        long effectiveTime = Long.valueOf(sessionTimeout) * 1000;
        if ("market_token".equals(token)) {
            return true;
        }
        Map<String, String> result = tokenMangerDao.findByToken(token);
        if (null == result || result.size() ==0) {
            return false;
        }
        String modifyTime = result.get("modify_time");
        if (StringUtil.isEmpty(modifyTime)) {
            return false;
        }
        long time1 = TimeConvertUtil.dateToMillisecond(TimeConvertUtil.mysqlTimeSubstring(modifyTime));
        long time2 = TimeConvertUtil.dateToMillisecond(TimeConvertUtil.getStringDate(new Date()));
        if(time2 - time1 > effectiveTime){
            boolean remove = remove(token);
            if (!remove) {
                logger.error("token删除失败");
            }
        }
        return true;
    }


}
